<template>
  <div class="dynamic-detail">
    <div class="header">
      <van-nav-bar
          title="动态详情"
          left-arrow
          @click-left="router.back()"
      />
    </div>
    <div class="detail">
      <div class="author-info">
        <van-image
            round
            width="40"
            height="40"
            :src="dynamic.avatar"
        />
        <div class="meta">
          <div class="name">{{ dynamic.nickname }}</div>
          <div class="time">{{ formatTime(dynamic.createTime) }} 第{{ dynamic.postCount }}贴</div>
        </div>
        <van-button
            size="mini"
            :type="dynamic.isFollowed ? 'default' : 'primary'"
            @click.stop="toggleFollow"
        >
          {{ dynamic.isFollowed ? '已关注' : '+ 关注' }}
        </van-button>
      </div>
      <div class="content">
        <div class="text">{{ dynamic.content }}</div>
        <div class="media-list">
          <template v-for="(media, index) in dynamic.media" :key="index">
            <div v-if="isVideo(media.url)" class="video-wrapper" @click="playVideo(media.url)">
              <van-image
                  :width="getMediaWidth(dynamic.media.length)"
                  :height="getMediaWidth(dynamic.media.length)"
                  fit="cover"
                  :src="media.cover || '/video.png'"
              />
              <van-icon name="play-circle" class="play-icon" />
            </div>
            <van-image
                v-else
                :width="getMediaWidth(dynamic.media.length)"
                :height="getMediaWidth(dynamic.media.length)"
                :src="media.url"
                @click="previewMedia(media.url, dynamic.media.map(m => m.url))"
            />
          </template>
        </div>
        <div class="tags">
          <van-tag plain type="primary" @click="showGroupDetail(dynamic.groupId)"># {{ dynamic.groupName }}</van-tag>
          <van-button
              icon="warning-o"
              size="mini"
          >举报</van-button>
        </div>
      </div>
    </div>

    <!-- 评论列表 -->
    <div class="comment-list">
      <div class="comment-header">
        全部评论（{{ dynamic.commentCount }}）
      </div>
      <div v-if="comments.length === 0 && !loading" class="no-comments">
        没有什么评论
      </div>
      <van-list
          v-model:loading="loading"
          :finished="finished"
          @load="loadComments"
      >
        <comment-item
            v-for="comment in comments"
            :key="comment.id"
            :comment="comment"
            @reply="handleReply"
            @like="handleLikeComment"
        />
      </van-list>
    </div>

    <!-- 评论输入框 -->
    <div class="comment-editor">
      <div class="editor-wrapper">
        <van-field
            v-model="commentForm.content"
            rows="1"
            autosize
            type="textarea"
            :placeholder="placeholderText"
            @click.stop="showEditor = true"
        />
        <!-- 点赞 -->
        <div class="action-item" @click="toggleLike(dynamic)" v-if="!showEditor">
          <van-icon
              :name="dynamic.isLiked ? 'good-job' : 'good-job-o'"
              :color="dynamic.isLiked ? '#ee0a24' : '#666'"
          />
          <span>{{ dynamic.likeCount }}</span>
        </div>
        <!-- 收藏 -->
        <div class="action-item" @click="toggleFavorite(dynamic)" v-if="!showEditor">
          <van-icon
              :name="dynamic.isFavorited ? 'star' : 'star-o'"
              :color="dynamic.isFavorited ? '#ffd700' : '#666'"
          />
        </div>
      </div>
      <div class="editor-actions" v-if="showEditor">
        <van-icon name="smile-o" @click="showEmoji = true" />
        <van-button
            size="small"
            type="primary"
            @click.stop="submitComment"
        >发送</van-button>
      </div>

      <!-- 表情选择 -->
<!--
   <van-popup
          v-model:show="showEmoji"
          position="bottom"
          round
      >
        <emoji-picker @select="onEmojiSelect" />
      </van-popup>
   -->

    </div>

    <!-- 弹窗：用于视频预览 -->
    <van-popup v-model:show="videoPreviewVisible" position="center" round>
      <video
          :src="currentVideoUrl"
          controls
          autoplay
          style="width: 100%; max-width: 600px; height: auto;"
      ></video>
    </van-popup>
  </div>
</template>

<script setup>
import { ref,onMounted, onUnmounted ,watch} from 'vue';
import { useRoute,useRouter } from 'vue-router';
 // import EmojiPicker from '@/components/EmojiPicker.vue';
import CommentItem from '@/components/CommentItem.vue';
import dayjs from 'dayjs';
import {showImagePreview,showToast}  from "vant";
import {followUser, getCommentList, publishComment,likeComment,likeDynamic,favoriteDynamic} from "@/api/index.js";

const router = useRouter();
const route = useRoute();
const dynamicId = route.params.dynamicId;
// 当前播放的视频地址
const videoPreviewVisible = ref(false);
const currentVideoUrl = ref('');
// 评论相关
const comments = ref([]);
const loading = ref(false);
const finished = ref(false);
const pageParams = ref({ page: 1, size: 10 });
// 输入相关
const showEditor = ref(false);
const showEmoji = ref(false);
const commentForm=ref({
  dynamicId:dynamicId,
  content:'',
  parentId:null,
  replyCommentId:null,
  replyUserId:null,
  replyUserName:null
})
const placeholderText=ref('文明发言，传递快乐...')

// 动态数据
const dynamic = ref({});

// 全局点击事件处理函数
const handleGlobalClick = (event) => {
  // 获取输入栏的 DOM 元素
  const editorElement = document.querySelector('.comment-editor');
  // 如果点击发生在输入栏外部，则收起输入栏
  if (!editorElement?.contains(event.target)) {
    showEditor.value = false;
    placeholderText.value="文明发言，传递快乐..."
    commentForm.value.content='';
    commentForm.value.parentId=null;
    commentForm.value.replyCommentId=null;
    commentForm.value.replyUserName=null;
    commentForm.value.replyUserId=null;
  }
};

// 在组件挂载时添加全局点击事件监听
onMounted(() => {
  dynamic.value= JSON.parse(localStorage.getItem('dynamic'))
  document.addEventListener('click', handleGlobalClick);
});

// 在组件卸载时移除全局点击事件监听
onUnmounted(() => {
  document.removeEventListener('click', handleGlobalClick);
});

// 判断是否为图片
const isImage = (url) => {
  return /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(url);
};

// 判断是否为视频
const isVideo = (url) => {
  return /\.(mp4|avi|mov|wmv|flv|mkv)$/i.test(url);
};

// 图片预览
const previewMedia = (currentMedia, mediaList) => {
  if (isImage(currentMedia)) {
    showImagePreview({
      images: mediaList.filter(isImage),
      startPosition: mediaList.indexOf(currentMedia),
      closeable: true,
    });
  }
};

// 播放视频
const playVideo = (videoUrl) => {
  currentVideoUrl.value = videoUrl;
  videoPreviewVisible.value = true;
};

const loadComments = async () => {
  try {
    // 调用API获取评论列表
    const res = await getCommentList({
      dynamicId: dynamicId,
      ...pageParams.value,
    });
    if (res.list.length > 0) {
      comments.value = [...comments.value, ...res.list];
      pageParams.value.page++;
    } else {
      finished.value = true;
    }
  }catch (error){
    console.error('评论列表加载失败:', error);
    finished.value = true;
  }finally {
    loading.value = false;
  }
};

const toggleFollow = async (dynamic) => {
  try {
    await followUser(dynamic.creator);
    dynamic.isFollowed = !dynamic.isFollowed;
  } catch (error) {
    console.error('关注操作失败:', error);
  }
};

const handleReply = (comment) => {
  placeholderText.value="回复"+comment.userName
  if(comment.parentId!=null) {
    commentForm.value.parentId=comment.parentId;
    commentForm.value.replyCommentId=comment.id;
    commentForm.value.replyUserName=comment.userName;
  }else {
    commentForm.value.parentId=comment.id;
  }
  commentForm.value.replyUserId = comment.userId;
  showEditor.value = true;
};

const handleLikeComment = async (updatedComment) => {
  try {
    await likeComment(updatedComment.id);
    // 找到对应评论索引
    const index = comments.value.findIndex(c => c.id === updatedComment.id);
    if (index !== -1) {
      // 替换整个对象以触发响应式更新
      comments.value.splice(index, 1, {
        ...updatedComment // 使用子组件传递的最新数据
      });
    }
  } catch (error) {
    console.error('点赞操作失败:', error);
  }
};

const submitComment = async () => {
  console.log(commentForm.value)
  if (!commentForm.value.content) {
    //提示输入内容不能为空
    showToast({
      message: '输入内容不能为空',
      duration: 1500,
    });
    return;
  }
  // 提交评论逻辑...
  try {
    await publishComment(commentForm.value);
    // 重置输入框
    commentForm.value.content = '';
    commentForm.value.parentId = null;
    commentForm.value.replyCommentId = null;
    commentForm.value.replyUserName = null;
    commentForm.value.replyUserId = null;
    showEditor.value = false;
    // 重新加载评论列表
    pageParams.value.page=1;
    comments.value = [];
    finished.value = false;
  } catch (error) {
    console.error('评论失败:', error);
  }
};

// 点赞操作
const toggleLike = async (dynamic) => {
  try {
    await likeDynamic(dynamic.id);
    dynamic.isLiked = !dynamic.isLiked;
    dynamic.likeCount += dynamic.isLiked ? 1 : -1;
  } catch (error) {
    console.error('操作失败:', error);
  }
};

// 收藏操作
const toggleFavorite = async (dynamic) => {
  try {
    await favoriteDynamic(dynamic.id);
    dynamic.isFavorited = !dynamic.isFavorited;
    dynamic.favoriteCount += dynamic.isFavorited ? 1 : -1;
  } catch (error) {
    console.error('操作失败:', error);
  }
};

// 时间格式化
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm');
};

const showGroupDetail = (groupId) => {
  router.push(`/groupDetail/${groupId}`);
};

// 计算媒体项宽度
const getMediaWidth = (count) => {
  if (count < 3) {
    return `calc(100% / ${count} - 5px)`;
  }
  return '110px';
};

// const onEmojiSelect = (emoji) => {
//   content.value += emoji;
// };
</script>

<style scoped>
.video-wrapper {
  position: relative;
  display: inline-block;
}

.play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 24px;
  color: rgba(255, 255, 255, 0.8);
  filter: drop-shadow(0 0 2px rgba(0, 0, 0, 0.5));
}

.media-list {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-top: 10px;
}
.dynamic-detail {
  padding-bottom: 60px;

  .author-info {
    display: flex;
    align-items: center;
    padding: 16px;
    gap: 12px;

    .meta {
      flex: 1;

      .name {
        font-weight: 500;
      }

      .time {
        color: #666;
        font-size: 12px;
      }
    }
  }

  .content {
    padding: 0 16px;

    h3 {
      margin: 0 0 8px 0;
    }

    .tags {
      margin-top: 12px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 8px;
    }
  }

  .comment-list {
    margin-top: 20px;

    .comment-header {
      padding: 8px 16px;
      color: #666;
      font-size: 14px;
      background: #f5f5f5;
    }
  }

  .comment-editor {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: white;
    padding: 8px;
    box-shadow: 0 -2px 8px rgba(0,0,0,0.1);

    .editor-actions {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-top: 8px;
    }
  }
}

.editor-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 20px;
  color: #666;

  &:active {
    opacity: 0.6;
  }
}

.no-comments {
  text-align: center;
  color: #999;
  font-size: 14px;
  margin-top: 24px;
}

.detail{
  padding:0px;
  margin-top: 46px;
}

.header{
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
}

</style>
